package com.aneliya.client.tcp;

import java.io.IOException;
import java.net.SocketException;
import java.net.SocketTimeoutException;

import com.aneliya.client.ClientListener;
import com.aneliya.io.IStreamStrategy;
import com.aneliya.model.Message;

public class TCPClientListener extends ClientListener {
	private static final int CLIENT_READ_TIMEOUT = 5*60*1000;
	
	private IStreamStrategy streamStrategy;
	public void setStreamStrategy(IStreamStrategy streamStrategy) {
		this.streamStrategy = streamStrategy;
	}
	
	public void configure() throws SocketException {
		TCPClient tcpClient = (TCPClient) client;
		tcpClient.getSocket().setSoTimeout(CLIENT_READ_TIMEOUT);
	}
	
	public void run() {
		try {
			while (!isInterrupted()) {
				try {
					Message message = streamStrategy.readMessage();
					if (message == null) {
						break;
					}
					handleMessage(message);
				} catch (SocketTimeoutException ex) {
					client.sendKeepAliveMessage();
				}
			}
		} catch (IOException ex) {
			// Communication problem
		}
		
		client.interruptClientSender();
		if (dispatcher.isClientAuthenticated(client)) {
			dispatcher.removeClient(client);
		}
	}

}
